<template>
  <div>
    <!-- 选择消息模板按钮 -->
    <t-button style="margin-right: 4px; margin-bottom: 4px;" theme="primary" @click="handleSelectMessage"
      v-if="!readonly">
      选择
    </t-button>
    <!-- 已选择的消息模板标签 -->
    <t-tag v-for="(tag, index) in selectedMessageIds" :key="index" style="margin-right: 4px; margin-bottom: 4px"
      theme="primary" :closable="!readonly" :disabled="readonly" @close="handleClose(index)">
      {{ tag.modelName }}
    </t-tag>

    <!-- 选择消息模板对话框 -->
    <t-dialog v-model:visible="visibleMessage" attach="body" header="选择消息模板" width="80%">
      <div class="container">
        <!-- 消息组树 -->
        <message-group-tree ref="messageGroupTreeRef" v-model:selected-id="selectedId" class="left" />
        <div v-show="selectedId" class="right">
          <!-- 自定义搜索 -->
          <custom-search ref="customSearchMessageRef" v-slot="{ params }" @submit="handleInitTableMessage">
            <t-col :span="3">
              <t-form-item label="模板名称" name="modelName">
                <t-input v-model:value="params.modelName" clearable placeholder="" />
              </t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="消息内容" name="message">
                <t-input v-model:value="params.message" clearable placeholder="" />
              </t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="是否超时发送" name="isTimeoutSend">
                <t-select v-model:value="params.isTimeoutSend" :options="dictionaryStore.get('is_type')" clearable
                  filterable placeholder="" />
              </t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="操作类型" name="operateType">
                <t-select v-model:value="params.operateType"
                  :options="dictionaryStore.get('decoration_order_operate_type')" clearable filterable placeholder="" />
              </t-form-item>
            </t-col>
          </custom-search>
          <!-- 自定义表格 -->
          <custom-table ref="customTableMessageRef" row-key="id" :columns="columnsMessage"
            :api="messageTemplateCRUD.page" column-controller-key="messageTemplateList">
            <template #isTimeoutSend="{ row }">
              {{ dictionaryStore.analysis('is_type', row.isTimeoutSend) }}
            </template>
            <template #operateType="{ row }">
              {{ dictionaryStore.analysis('decoration_order_operate_type', row.operateType) }}
            </template>
            <template #operation="{ row }">
              <t-space>
                <t-link theme="primary" @click="handleSelectedIds(row)">
                  选择
                </t-link>
              </t-space>
            </template>
          </custom-table>
        </div>
        <t-empty v-show="!selectedId" class="right" title="请先选择部门" style="margin-top: 250px" />
      </div>
      <template #footer>
        <div style="display: flex; justify-content: space-between">
          <div>
            已选择的消息配置：
            <t-tag style="margin-right: 4px" v-for="(tag, index) in messageList" :key="index" theme="primary"
              :closable="true" @close="handleCloseDialog(index)">
              {{ tag.modelName }}
            </t-tag>
          </div>
          <div>
            <t-button theme="default" @click="visibleMessage = false">取消</t-button>
            <t-button theme="warning" @click="handleReset">重置</t-button>
            <t-button :loading="loadingSubmit" @click="handleSave">保存</t-button>
          </div>
        </div>
      </template>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, useTemplateRef } from 'vue';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { useDictionaryStore } from '@/store';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import MessageGroupTree from '@/pages/config/message-group/components/MessageGroupTree.vue';
import { messageTemplateCRUD } from '@/api/config/message-template';

// 字典仓库
const dictionaryStore = useDictionaryStore();

// 组件 props
const props = defineProps({
  selectedMessageIds: {
    type: Array,
    default: () => [],
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  multiple: {
    type: Boolean,
    default: false,
  }
});

// 组件 emits
const emits = defineEmits(['update:selectedMessageIds']);

// 控制对话框显示
const visibleMessage = ref(false);

// 选择的 id
const selectedId = ref();

// 消息列表
const messageList = ref<Record<string, any>[]>([]);

// 加载状态
const loadingSubmit = ref(false);

// 处理选择消息模板
const handleSelectMessage = () => {
  visibleMessage.value = true;
  messageList.value = [...props.selectedMessageIds];
};

// 处理删除已选择的消息模板
const handleClose = (index: number) => {
  const newSelectedMessageIds = [...props.selectedMessageIds];
  newSelectedMessageIds.splice(index, 1);
  emits('update:selectedMessageIds', newSelectedMessageIds);
};

// 处理保存
const handleSave = () => {
  emits('update:selectedMessageIds', messageList.value);
  visibleMessage.value = false;
};

// 处理重置
const handleReset = () => {
  messageList.value = [];
};

// 处理删除对话框中的消息模板
const handleCloseDialog = (index: number) => {
  messageList.value.splice(index, 1);
};

// 处理选择消息模板
const handleSelectedIds = (row: any) => {
  if (props.multiple) {
    if (!messageList.value.some((item) => item.id === row.id)) {
      messageList.value.push(row);
      MessagePlugin.success('该消息配置选择成功');
    } else {
      MessagePlugin.error('该消息配置已被选择');
    }
  } else {
    messageList.value = [row]
  }

};
// 自定义搜索ref
const customSearchMessageRef = useTemplateRef('customSearchMessageRef');
// 自定义表格ref
const customTableMessageRef = useTemplateRef('customTableMessageRef');
// columnsMessage
const columnsMessage: TableCol[] = [
  { colKey: 'modelName', title: '模板名称' },
  { colKey: 'message', title: '消息内容', width: 450 },
  { colKey: 'isTimeoutSend', title: '是否超时发送' },
  { colKey: 'timeout', title: '超时时间' },
  { colKey: 'operateType', title: '操作类型' },
  { colKey: 'operation', title: '操作', fixed: 'right' },
];
// 处理初始化表格
const handleInitTableMessage = () => {
  const params = {
    ...customSearchMessageRef.value.params,
    parentId: selectedId.value,
  };
  customTableMessageRef.value.initTable(params);
};
watch(
  () => selectedId.value,
  (newValue) => {
    if (newValue) handleInitTableMessage();
  },
);
</script>

<style lang="less" scoped>
.container {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  @leftWidth: 300px;

  .left {
    width: @leftWidth;
  }

  .right {
    width: calc(100% - @leftWidth);
  }
}
</style>